package dao.base;

import constants.DbConstants;
import dao.base.Dao;
import dao.hikari.HikariDataSourceInstance;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public abstract class BaseDao<T> implements Dao<T> {

    /**
     * 从HikariCP中获取数据库连接
     * @return
     */
    final protected static Connection getHikariConn() {
        try {
            Connection conn = HikariDataSourceInstance.getHikariDataSource().getConnection();
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用原生方式获取数据库连接，需要在使用后手动关闭连接
     * @return
     */
    final protected static Connection getNativeConn() {
        String driver = DbConstants.driver;
        String url = DbConstants.url;
        String username = DbConstants.username;
        String password = DbConstants.password;

        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return conn;
    }

}
